package com.rules.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rules.admin.utils.ResultUtils;
import com.gillion.grule.client.core.variable.PackageVariable;
import com.rules.admin.entity.RuleVariable;
import com.rules.admin.service.RuleVariableService;
import com.rules.admin.utils.TypeTransform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({"/variables"})
public class VariableController {
   private static final Logger LOGGER = LoggerFactory.getLogger(TypeTransform.class);
   @Autowired
   private RuleVariableService ruleVariableService;

   @RequestMapping(
      value = {"/test"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public PackageVariable loadPackageVariable(@RequestParam Long packageId) {
      return this.ruleVariableService.loadCompletelyPackageVaribles(packageId);
   }

   @RequestMapping(
      value = {"/{scope}/{scopeId}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public List<RuleVariable> getGlobalVariable(@PathVariable("scope") Integer scope, @PathVariable Long scopeId) {

      return this.ruleVariableService.getByScopeAndScopeId(scope,scopeId);
   }

   @RequestMapping(
      value = {"/{scope}/{scopeId}"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> addGlobalVariable(@RequestBody RuleVariable ruleVariable) {

      List<RuleVariable> ruleVariables = this.ruleVariableService.getByScopeId(ruleVariable.getScopeId());
      if (ruleVariables.stream().filter((variables) -> {
         return variables.getVarName().equals(ruleVariable.getVarName());
      }).count() > 0L) {
         return ResultUtils.getFaildResultData(new String[]{"变量名称不能重复！"});
      } else {
         this.ruleVariableService.save(ruleVariable);
         return ResultUtils.getSuccessResultData(ruleVariable);
      }
   }

   @RequestMapping(
      value = {"/{scope}/{scopeId}/{id}"},
      method = {RequestMethod.DELETE}
   )
   @ResponseBody
   public Map<String, Object> deleteGlobalVariable(@PathVariable("id") Long id) {
      this.ruleVariableService.removeById(id);
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      value = {"/{scope}/{scopeId}/{id}"},
      method = {RequestMethod.PUT}
   )
   @ResponseBody
   public Map<String, Object> updateGlobalVariable(@RequestBody RuleVariable ruleVariable) {
      this.ruleVariableService.updateById(ruleVariable);
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      value = {"/assembly/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getAssemblyVariable(@PathVariable("id") Long id) {
      List<RuleVariable> list = this.ruleVariableService.loadAssemblyVariablesById(id);
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/rule/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getRuleVariable(@PathVariable("id") Long id) {
      List<RuleVariable> list = this.ruleVariableService.loadRuleVariablesById(id);
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/package/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getPackageVariable(@PathVariable("id") Long id) {
      List<RuleVariable> list = this.ruleVariableService.loadPackageVariables(1, id);
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/decisionTable/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getDecisionTableVariable(@PathVariable("id") Long id) {
      List<RuleVariable> list = this.ruleVariableService.loadDecisionTableVariables(id);
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      value = {"/decisionTree/{id}"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public Map<String, Object> getDecisionTreeVariable(@PathVariable("id") Long id) {
      List<RuleVariable> list = this.ruleVariableService.loadDecisionTreeVariables(id);
      return ResultUtils.getSuccessResultData(list);
   }

   @RequestMapping(
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public List<RuleVariable> getVariable(@RequestParam Integer scope, Long scopeId) {
      return this.ruleVariableService.getByScopeAndScopeId(scope,scopeId);
   }

   @RequestMapping(
      value = {"/addFromJson"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> create(HttpServletRequest request, HttpServletResponse response, Long scopeId, Integer scope) {
      MultipartHttpServletRequest multipartRequest;
      try {
         multipartRequest = (MultipartHttpServletRequest)request;
      } catch (Exception var12) {
         LOGGER.error("获取传入的文件失败！", var12);
         return ResultUtils.getFaildResultData(new String[]{"导入失败，请检查数据格式！"});
      }

      MultipartFile multipartFile = multipartRequest.getFile("file");

      try {
         String jsonstr = TypeTransform.inputStream2String(multipartFile.getInputStream());
         JSONArray list = JSON.parseArray(jsonstr);
         Iterator var9 = list.iterator();

         while(var9.hasNext()) {
            Object obj = var9.next();
            JSONObject jsonObj = (JSONObject)obj;
            this.map2Data(jsonObj, scope, scopeId);
         }
      } catch (Exception var13) {
         LOGGER.error("导入失败！", var13);
         return ResultUtils.getFaildResultData(new String[]{"导入失败，请检查数据格式！"});
      }

      return ResultUtils.getSuccessResultData();
   }

   public void map2Data(JSONObject obj, Integer scope, Long scopeId) {
      RuleVariable rv = new RuleVariable();
      if ("1".equals(obj.get("valueType").toString())) {
         rv.setVarValueExpr("'" + obj.get("varValueExpr").toString() + "'");
      } else {
         rv.setVarValueExpr(obj.get("varValueExpr").toString());
      }

      rv.setScope(scope);
      rv.setScopeId(scopeId);
      rv.setValueType(Integer.parseInt(obj.get("valueType").toString()));
      rv.setVarName(obj.get("varName").toString());
      this.ruleVariableService.save(rv);
   }
}
